package com.hbhmzy.call;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.hbhmzy.contact.ContactsActivity;


/**
 * 通讯录
 * Activities that contain this fragment must implement the
 *
 */
public class AddressFragment extends Fragment implements View.OnClickListener{

    private static final int REQUEST_READ_CONTACTS_PERMISSION = 3;

    private View view;
    private TextView mTextview;
    private Button mBtnAddress;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_address, container, false);
        initView();
        return view;
    }

    private void initView() {
        mTextview = view.findViewById(R.id.mTextview);
        mBtnAddress = view.findViewById(R.id.mButton);
        mBtnAddress.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.READ_CONTACTS},
                    REQUEST_READ_CONTACTS_PERMISSION);
        }else {
            toContactsActivity();
        }
    }

    private void toContactsActivity(){
//        if(ContactsActivity.isFinish){
            Intent intent=new Intent(getActivity(),ContactsActivity.class);
            startActivity(intent);
//        }else {
//            Toast.makeText(getActivity(), "您的操作太频繁啦~",Toast.LENGTH_SHORT).show();
//        }
    }

    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_READ_CONTACTS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                toContactsActivity();
            }else {
                Toast.makeText(getActivity(), "未获取通讯录权限，请在权限设置中进行设置", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
